// 函数组件 imr + slr
// 类组件 imrc + ccs

import React, { Component } from "react";

class App extends Component {
  state = {
    value: "",
    list: [
      {
        id: 1,
        name: "tom",
      },
      {
        id: 2,
        name: "jerry",
      },
    ],
  };

  fn = (e) => {
    this.setState({
      value: e.target.value,
    });
  };

  add = () => {
    if (this.state.value) {
      this.setState((prevState) => {
        return {
          list: [
            ...prevState.list,
            { id: new Date().getTime(), name: this.state.value },
          ],
          value: "",
        };
      });
    }
  };

  fn2 = (e) => {
    if (e.key === "Enter") {
      this.add();
    }
  };

  remove = (id) => () => {
    this.setState((prevState) => {
      const newArr = prevState.list.filter((item) => item.id !== id);
      return {
        list: newArr,
      };
    });
  };

  render() {
    return (
      <>
        <h2>todolist</h2>
        <input
          type="text"
          value={this.state.value}
          onChange={this.fn}
          onKeyUp={this.fn2}
        />
        <button onClick={this.add}>新增</button>

        <ul>
          {this.state.list.map((item) => (
            <li key={item.id}>
              {item.name} - <button onClick={this.remove(item.id)}>删除</button>
            </li>
          ))}
        </ul>
      </>
    );
  }
}

export default App;
